package br.com.iswe.gwt.crud.client;

import java.util.List;

import br.com.iswe.core.entidades.gwt.BeanMap;
import br.com.iswe.gwt.ui.client.CheckBoxBag;
import br.com.iswe.gwt.ui.client.MessagePanel;
import br.com.iswe.gwt.ui.client.QueryInfo;
import br.com.iswe.gwt.ui.client.service.BeanMapServiceClientImpl;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;

public abstract class BeanMapListPanel extends ListPanelAbstract<BeanMap> {

	protected void searchImpl(final QueryInfo queryInfo) {
		//Get the service
		BeanMapServiceClientImpl service = (BeanMapServiceClientImpl)listPanelListener.getService();
		//Build the filter
		BeanMap filter = listPanelListener.buildFilter();
		//execute the remote service
		service.consultar(filter, queryInfo, new AsyncCallback<List<BeanMap>>(){
			public void onFailure(Throwable caught) {
				MessagePanel.getInstance().showError(caught, "Error searching !");
			}
			public void onSuccess(List<BeanMap> queryResult) {
				populate(queryResult);
				//if there is any result notify the total of pages back to the pagination component
				if(queryResult.size() > 0){
					getPaginationPanel().notifyPageWithResult(queryInfo.getNumeroPagina());
				}
			}});
	}

	public void clear(){
		//clean the felxTable
		while(getFlexTable().getRowCount() > 1){
			getFlexTable().removeRow(1);
		}
		checkBoxList.clear();
	}
	
	public void populate(List<BeanMap> queryResult) {
		clear();
		
		int row = 0;
		for (int i = 0; i < queryResult.size(); i++) {
			final BeanMap item = queryResult.get(i);
			row = getFlexTable().getRowCount();
			
			buildRow(row, item);
			
			if((row % 2) == 0){
				getFlexTable().getRowFormatter().setStyleName(row, "iswe-listRowPar");
			}
			else{
				getFlexTable().getRowFormatter().setStyleName(row, "iswe-listRowImpar");
			}
		}
		
		//create the on change event for every checkbox created
		for(CheckBoxBag item : checkBoxList){
			item.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
				
				public void onValueChange(ValueChangeEvent<Boolean> event) {
					notifyCheckBoxValueChanged();
				}
			});
		}
		
		if(hasPagination()){
			int cols = getFlexTable().getCellCount(row);
			
			row = getFlexTable().getRowCount();
			PaginationPanel paginationPanel = getPaginationPanel();
			getFlexTable().setWidget(row, 0, paginationPanel);
			getFlexTable().getFlexCellFormatter().setColSpan(row, 0, cols);
			getFlexTable().getFlexCellFormatter().setAlignment(row, 0, HasHorizontalAlignment.ALIGN_CENTER, HasVerticalAlignment.ALIGN_MIDDLE);
		}	
	}
	
	protected abstract void buildRow(int row, BeanMap item);
}
